package com.bubaiwantong.algorithms.insert;

/**
 * @author bubaiwantong
 * @description
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] arr = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        ShellSort shellSort = new ShellSort();
        shellSort.print(arr);
        shellSort.sort(arr);
        shellSort.print(arr);
    }

    /**
     * 希尔排序也属于插入排序，这是历史上第一个将时间复杂度降到o(n^2)的排序算法
     *
     * @param arr
     */
    public void sort(int[] arr) {
        for (int gap = 4; gap > 0; gap /= 2) {
            for (int i = gap; i < arr.length; i++) {
                int temp = arr[i];
                int j = i - gap;
                while (j >= 0 && arr[j] > temp) {
                    arr[j + gap] = arr[j];
                    j -= gap;
                }
                arr[j + gap] = temp;
            }
        }
    }

    public void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }


}
